<template>
	<view class="main">
		<view class="card1">
			<view class="title">
				<h2>异常原因：</h2>
			</view>
			<view class="tag-part">
				<template v-for="(item,index) in tagDatas">
					<view class="tag-view" :key="index">
						<u-tag :text="item.label" class="tag-part" @click="tagChange(item,index)" type="error"
							:mode="tagCurrent===index?'dark':'plain'" />
					</view>
				</template>
			</view>
		</view>
		<view class="card5">
			<view class="item" v-for="(item,index) in detailDatas['card5']" :key="index">
				<view class="label-part">
					{{ item.label+'：'}}
				</view>
				<view class="text-part">
					{{ item.prop ?  query[item.prop]:''}}
				</view>
			</view>
			<view class="item" v-if="!isBeging">
				<view class="label-part">
					异常状态：
				</view>
				<view class="text-part">
					{{ resolutionStatus}}
				</view>
			</view>
		</view>
		<view class="card2">
			<view class="label-part">
				持续时间：
			</view>
			<view class="time-part">
				{{ duration.hours + ':' + duration.minutes + ':' + duration.seconds }}
			</view>
			<view class="button-part">
				<view class="circle1" :class="isBeging?'start':'end'"
					v-if="isBeging||(!isBeging&&(tableDatas.datas.length?!tableDatas.datas[0].EndDate:true))">
					<view class="circle0" @click="handleClick">异常<br>{{isBeging?'开始':'结束'}}</view>
				</view>
			</view>
			<!-- <view class="remark-part">
				发起15分钟后正式提交
			</view> -->
		</view>
		<view class="card3" v-if="!isBeging&&tableDatas.datas.length">
			<view class="item" v-for="(item,index) in detailDatas['card3']" :key="index">
				<view class="label-part">
					{{ item.label+'：'}}
				</view>
				<view class="text-part">
					{{ item.prop?  tableDatas.datas[0][item.prop]:''}}
				</view>
			</view>
		</view>
		<view class="card4" v-if="isBeging">
			<view class="item">
				<view class="label-part label-part-4-1">
					图号：
				</view>
				<view class="text-part">
					<u-input v-model="form.ChildMaterialCode" border></u-input>
				</view>
			</view>
			<view class="item card-item">
				<view class="label-part label-part-4-1">
					异常描述：
				</view>
				<view class="text-part">
					<u-input type="textarea" v-model="form.AbnormalDescription" class="input-textarea" border></u-input>
				</view>
			</view>
		</view>
		<!-- 上传图片 -->
		<view class="card4">
			<view class="item card-item">
				<view class="label-part ">
					<span>图片/视频：</span>
				</view>
				<view class="text-part">
					<!-- 上传组件测试 -->
					<htz-image-upload ref="uploadRef" :max="5" v-model="uploadDatas.fileList" mediaType="all"
						:formData="uploadDatas.formData" :compress="false" @chooseSuccess="chooseFile" :dataType="1"
						:remove="!uploadDatas.id" :add="!uploadDatas.id"></htz-image-upload>
				</view>
			</view>
		</view>
		<!-- 确定操作弹窗 -->
		<view>
			<u-popup v-model="confirmStatus" mode="center">
				<view class="confirm-main">
					<view class="confirm-title">异常还未处理，是否继续结束异常?</view>
					<view class="button-part">
						<u-button class="btn" @click="confirmStatus = false" plain type='error'>取消</u-button>
						<u-button class="btn" @click="confirm" plain type='primary'>确定</u-button>
					</view>
				</view>

			</u-popup>
		</view>

	</view>
</template>

<script>
	import htzImageUpload from '@/components/htz-image-upload/htz-image-upload.vue'
	// 开始异常
	export default {
		components: {
			htzImageUpload
		},
		data() {
			return {
				isBeging: true,
				rowData: null,
				tagDatas: [],
				tableDatas: {
					ID: 24401,
					datas: [],
					columns: [],
					condition: {},
					selectRow: null
				},
				form: {
					AbnormalDescription: '',
					ChildMaterialCode: '',
				},
				tagCurrent: -1,
				detailDatas: {
					card3: [{
							prop: 'StartDate',
							label: '开始时间'
						},
						{
							prop: 'EndDate',
							label: '结束时间'
						},
					],
					card4: [{
							prop: 'ChildMaterialCode',
							label: '图号',
							type: 'select'
						},
						{
							prop: 'AbnormalDescription',
							label: '异常描述',
							type: 'textarea'
						},

					],
					card5: [{
							prop: 'SourceOrderNo',
							label: 'PO单号'
						},
						{
							prop: 'PreparePlanName',
							label: '任务名称'
						},
						{
							prop: 'MaterialName',
							label: '组件名称'
						}
					],
				},
				query: {},
				uploadDatas: {
					action: 'http://218.13.39.165:9999/APSAPI/UploadAbnomalImages',
					formData: {},
					fileList: [],
					timestamp: '',
					id: null,
					type: 'video',
					videoPath: ''
				},
				timer: null,
				duration: {
					hours: '00',
					minutes: '00',
					seconds: '00'
				},
				confirmStatus: false,
			};
		},
		computed: {
			imageDatas() {
				// const filePath = this.tableDatas.datas[0]?.FilePath.split(',') || []
				const url = uni.getStorageSync('url') || ''
				return this.tableDatas.datas[0]?.FilePath?.split(',').map(val => ({
					type: val.includes('AbnormalVideo') ? 1 : 0,
					path: url + val
				})) || []
			},
			resolutionStatus() {
				const data = this.tableDatas.datas
				return !data.length ? '' : data[0].ResolutionStatus ? '已处理' : data[0].ResolutionStartDate ? '处理中' : '未处理'
			}

		},
		onLoad(e) {
			this.query = e
			if (e.isBeging && e.isBeging === 'false') this.isBeging = false
			if (!this.isBeging && !e.ID) console.log('没有ID')
			else this.uploadDatas.id = e.ID
			this.getAbnormalOptions().then(() => {
				if (!this.isBeging) {
					this.getApsData().then(() => {
						const AbnormalReasonID = this.tableDatas.datas[0].AbnormalReasonID
						this.tagCurrent = this.tagDatas.findIndex(val => val.value === AbnormalReasonID)
						this.startTiming()
					})

				}
			})
		},
		methods: {
			fileChange(lists) {
				this.uploadDatas.fileList = lists
			},
			tagChange(item, index) {
				if (!this.isBeging) return
				this.tagCurrent = index
			},
			async handleClick() {
				let message = ''
				if (this.isBeging) {
					// 异常开始
					if (!this.form.AbnormalDescription) message = '填写异常描述'
					if (!this.form.ChildMaterialCode) message = '填写图号'
					if (this.uploadDatas.id) message = '异常已提交'
					if (this.tagCurrent < 0) message = '请选择异常类型'
					// if(!this.form.)
					if (message) return uni.showToast({
						title: message,
						icon: 'none'
					})
					const timestamp = this.$u.timeFormat(new Date(), 'yyyymmddhhMMss')
					this.uploadDatas.timestamp = timestamp
					const rowData = this.query
					rowData.AbnormalReasonID = this.tagDatas[this.tagCurrent].value
					Object.assign(rowData, this.form)
					const res = await this.$request.post({
						url: '/APSAPI/HandleTaskManagement',
						data: [rowData]
					}).catch(err => err)
					if (!res) return
					const {
						msg,
						id
					} = res
					this.uploadDatas.id = id
					this.uploadDatas.formData.nickName = this.query.SourceOrderNo
					this.uploadDatas.formData.id = id
					this.uploadDatas.formData.dicID = 24400
					this.uploadDatas.formData.resolutionStatus = 0 // 异常0 异常处理1
					if (this.uploadDatas.fileList.length) {
						this.$refs.uploadRef.imgUpload2(this.uploadDatas.fileList, this.uploadDatas.action)
							.then(() => {
								this.$set(this, 'isBeging', false)
								this.getApsData().then(() => {
									uni.showToast({
										title: '异常提交成功！',
										icon: 'success'
									})
									this.startTiming()
								})
							}).catch((err) => {
								this.$set(this, 'isBeging', false)
								this.getApsData().then(() => {
									uni.showToast({
										title: '异常提交成功。但图片上传失败！',
										icon: 'error'
									})
									this.startTiming()
								})
							})
					} else {
						this.$set(this, 'isBeging', false)
						this.getApsData().then(() => {
							this.startTiming()
						})
					}
				} else {
					if (this.resolutionStatus === '未处理') message = '异常还是未处理，是否确定结束异常?'
					if (this.resolutionStatus === '处理中') message = '异常还在处理中，是否确定结束异常?'
					//EndDate
					if (this.tableDatas.datas?.[0]?.EndDate) return // 如果有结束时间，判断已结束返回
					//如果异常未处理，需要确认时候继续操作
					if (message) {
						this.confirmStatus = true
						return
					}
					// 结束异常
					const condition = JSON.parse(JSON.stringify(this.query))
					condition.SubmitType = 5
					const res = await this.$request.post({
						url: '/APSAPI/HandleTaskManagement',
						data: [condition]
					}).catch(err => err)
					if (!res) return
					const {
						msg
					} = res
					clearInterval(this.timer);
					this.getApsData().then(() => {
						uni.showToast({
							title: msg,
							icon: 'success'
						})
					})
				}
			},
			async getAbnormalOptions() {
				const condition = {
					dicID: 7770,
				}
				const res = await this.$request.post({
					url: '/APSAPI/APSData',
					data: condition
				}).catch(err => err)
				if (!res) return
				const {
					data
				} = res
				this.$set(this, 'tagDatas', data.map(val => {
					return {
						label: val.SmallType,
						value: val.AbnormalReasonID
					}
				}))
			},
			// 获取数据
			async getApsData(remark = 0) {
				const condition = {
					dicID: this.tableDatas.ID
				}
				condition.ID = this.uploadDatas.id
				const res = await this.$request.post({
					url: '/APSAPI/APSData',
					data: condition
				}).catch(err => err)
				const {
					result,
					msg,
					data,
					Columns
				} = res
				if (!result) return uni.showToast({
					title: msg,
					icon: 'error'
				})
				this.$set(this.tableDatas, 'datas', data)
				if (data.length && data[0].FilePath) {
					const url = uni.getStorageSync('url') || ''
					this.$set(this.uploadDatas, 'fileList', data[0]?.FilePath?.split(',').map(val => ({
						type: val.includes('AbnormalVideo') ? 1 : 0,
						url: url + val
					})) || [])
				}
				this.$set(this.tableDatas, 'columns', Columns[0])
			},
			//开始计时
			startTiming() {
				const start = new Date(this.tableDatas.datas[0].StartDate)
				if (this.tableDatas.datas[0]?.EndDate) {
					const now = new Date(this.tableDatas.datas[0]?.EndDate);
					const diff = now - start; // 计算时间差，单位为毫秒
					const hours = Math.floor(diff / (1000 * 60 * 60));
					const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
					const seconds = Math.floor((diff % (1000 * 60)) / 1000);
					if (hours > 99) {
						this.duration = {
							hours: 100,
							minutes: 0,
							seconds: 0
						};
					} else {
						this.duration = {
							hours: hours < 10 ? '0' + hours : hours,
							minutes: minutes < 10 ? '0' + minutes : minutes,
							seconds: seconds < 10 ? '0' + seconds : seconds,
						};
					}
				} else {
					this.timer = setInterval(() => {
						const now = new Date();
						const diff = now - start; // 计算时间差，单位为毫秒
						const hours = Math.floor(diff / (1000 * 60 * 60));
						const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
						const seconds = Math.floor((diff % (1000 * 60)) / 1000);
						if (hours > 99) {
							this.duration = {
								hours: 100,
								minutes: 0,
								seconds: 0
							};
						} else {
							this.duration = {
								hours: hours < 10 ? '0' + hours : hours,
								minutes: minutes < 10 ? '0' + minutes : minutes,
								seconds: seconds < 10 ? '0' + seconds : seconds,
							};
						}
					}, 1000);
				}


			},
			// 确定继续操作
			async confirm() {
				this.confirmStatus = false
				// 结束异常
				const condition = JSON.parse(JSON.stringify(this.query))
				condition.SubmitType = 5
				const res = await this.$request.post({
					url: '/APSAPI/HandleTaskManagement',
					data: [condition]
				}).catch(err => err)
				if (!res) return
				const {
					msg
				} = res
				clearInterval(this.timer);
				this.getApsData().then(() => {
					uni.showToast({
						title: msg,
						icon: 'success'
					})
				})
			},
			chooseFile(filePaths, type) {
				filePaths.forEach(val => {
					this.uploadDatas.fileList.push({
						type: type,
						url: val
					})
				})
			},
		},
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer);
			}
		},


	}
</script>

<style lang="scss" scoped>
	.main {
		background-color: $uni-bg-color-grey;
		width: 100%;
		height: 100%;
		min-height: 100vh;
	}

	.tag-part {
		text-wrap: nowrap;
		text-overflow: ellipsis;
		// max-width: 100%;
		width: 100%;
		overflow: hidden;
		font-size: 24rpx;
	}

	.card1,
	.card2,
	.card3,
	.card4,
	.card5 {
		background-color: $uni-bg-color;
		margin-bottom: 10rpx;
		padding: 20rpx 20rpx;
		width: 100%;
	}

	.card1 {
		display: flex;
		flex-wrap: wrap;
		width: 100%;
		flex-direction: column;

		.title {
			color: $uni-color-error;
		}

		.tag-part {
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			margin-top: 20rpx;

			.tag-view {
				max-width: 25%;
				margin-right: 15rpx;
			}
		}

	}

	.label-part {
		display: flex;
		align-items: center;
		color: $uni-text-color-placeholder;
		justify-content: flex-end;
		width: 150rpx;
		min-width: 150rpx;
		font-size: small;
	}

	.label-part-1 {
		display: flex;
		justify-content: space-between;

		.check {
			color: skyblue;
		}
	}

	.label-part-4-1 {
		align-items: start;
		padding: 10rpx 0;
	}

	.card2 {
		display: flex;
		flex-wrap: nowrap;
		position: relative;

		.label-part {
			align-items: center;
		}

		.remark-part {
			position: absolute;
			bottom: 10rpx;
			font-size: 20rpx;
			color: $uni-text-color-placeholder;
			left: 50%;
			left: 50%;
			/* 左边距设置为父元素宽度的50% */
			transform: translateX(-50%);
		}

		.time-part {
			flex-grow: 1;
			display: flex;
			align-items: center;
			color: $uni-color-error;
			font-size: 60rpx;
			padding: 0 0 0 10rpx;
		}

		.button-part {
			// width:;
			padding: 0 10rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			.start {
				background-color: rgb(250, 181, 80, 0.4);

				>* {
					background-color: #fab451;
				}
			}

			.end {
				background-color: rgb(81, 131, 255, 0.4);

				>* {
					background-color: rgb(81, 131, 255);
				}
			}

			.circle1 {

				width: 150rpx;
				height: 150rpx;
				border-radius: 50%;
				display: flex;
				justify-content: center;
				align-items: center;

				.circle0 {
					width: 130rpx;
					height: 130rpx;
					border-radius: 50%;
					font-size: 30rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					color: #fff;

				}

			}
		}
	}

	.card-item {
		.label-part {
			align-items: flex-start;
		}
	}

	.card3,
	.card4,
	.card5 {
		display: flex;
		flex-direction: column;

		.item {
			display: flex;
			flex-wrap: nowrap;
			overflow: hidden;
			margin-bottom: 10rpx;
		}

		.text-part {
			flex-grow: 1;
			color: #000;
			text-indent: 5rpx;
			padding-left: 10rpx;
			text-wrap: wrap;
		}
	}

	.confirm-main {
		display: flex;
		flex-direction: column;
		padding: 30rpx 0;

		.confirm-title {
			font-size: small;
			padding: 10rpx 20rpx;
		}

		.button-part {
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			align-items: center;

			.btn {
				width: 40%;
			}
		}
	}

	.upload-video-main {
		width: 100px;
		height: 100px;
		margin: 5px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #f4f5f6;

		.text {
			margin-top: 11px;
			line-height: 22px;
			font-size: 14px;
		}
	}
</style>